<template>
  <div class="source">
    <div class="inputDiv">
      <h2 class="img-title">
        <span>商品信息</span>
      </h2>
      <el-form label-position="top">
        <el-form-item>
          <label class="item-title">
            {{ $t('productCenter.catelog') }}
            <b>*</b>
          </label>
          <br />
          <el-cascader
            :disabled="operationType === 'edit' || operationType === 'preview'"
            :clearable="true"
            :options="catelogList"
            :placeholder="$t('productCenter.selectCatelog')"
            :props="props"
            v-model="oneData.selCateId"
            @change="changeCatelogId"
            :filter-method="handleCatelogFilter"
            filterable
          >
            <template slot-scope="{ data }">
              <span v-if="data.catalogName.length <= 50">{{
                data.catalogName
              }}</span>
              <ellipsis v-else tooltip :length="50">{{
                data.catalogName
              }}</ellipsis>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <label class="item-title">
            商品类型
            <b>*</b>
          </label>
          <el-select v-model="oneData.productType" :disabled="isPreview" placeholder="请选择">
            <el-option
              v-for="item in lookupItems.PRODUCTTYPE"
              :key="item.dicCode"
              :label="item.dicName"
              :value="item.dicCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <label class="item-title">
            商品名称
            <b>*</b>
            </label>
          <el-input v-model="oneData.productName"  @input="oneData.productName=oneData.productName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')" :disabled="isPreview" placeholder=""></el-input>
        </el-form-item>
        <el-form-item>
          <label class="item-title">
            商品描述
            </label>
          <el-input type="textarea" :disabled="isPreview" v-model="oneData.productDescribe" @input="oneData.productDescribe=oneData.productDescribe.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')" placeholder=""></el-input>
        </el-form-item>
        <el-form-item prop="productCategory" style="margin-bottom: 15px">
          <label class="item-title">
            商品标签
            <b>*</b>
          </label>
          <br />
          <div class="cateBox">
            <el-tag
              v-for="tag in tagDatas"
              :key="tag.id"
              :closable='!isPreview'
              @close="removeLabel(tag)"
              type="success"
              >{{ tag.labelName }}</el-tag
            >
            <!-- </span> -->
            <i class="el-icon-plus" @click="showAddLabel" v-if="!isPreview"></i>
          </div>
          <add-label ref="addLabel" @getTagList="getTagList"></add-label>
        </el-form-item>
        <el-form-item prop="productCategory" style="margin-bottom: 15px">
          <label class="item-title">
            前台类目
            <b>*</b>
          </label>
          <br />
          <div class="cateBox">
            <span v-for="(channel, key) in model.categoryDatas" :key="key">
              <el-tag
                v-for="(tag, index) in channel"
                :key="tag.id"
                :closable='!isPreview'
                @close="removeCate(index, key)"
                type="success"
                >{{ tag.label }}</el-tag
              >
            </span>
            <i class="el-icon-plus" @click="showAddCate" v-if="!isPreview"></i>
          </div>
          <add-Categories
            ref="addCate"
            :orgList="selectedOrgList"
            :countryTypes="countryTypes"
            v-if="addDialogShow"
            @closeDialog="closeCate"
            :categoryList="model.categoryDatas"
            @setValue="setCate"
          ></add-Categories>
        </el-form-item>
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="cancelable">
                <label class="item-title">
                  积分兑换
                  <b>*</b>
                </label>
                <br />
                <el-radio :disabled="isPreview" v-model="oneData.isCreditsExchange" label="1">是</el-radio>
                <el-radio :disabled="isPreview" v-model="oneData.isCreditsExchange" label="0">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="returnable">
                <label class="item-title">
                  是否配送
                  <b>*</b>
                </label>
                <br />
                <el-radio :disabled="isPreview" v-model="oneData.isDelivery" label="1">是</el-radio>
                <el-radio :disabled="isPreview" v-model="oneData.isDelivery" label="0">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div class="inputDiv">
      <h2 class="img-title">
        <span>{{ $t('productCenter.productImages') }}</span>
      </h2>
      <el-form class="spu-img" ref="spuImgForm" :model="spuImgForm">
        <el-form-item prop="spuImgList" style="margin-top: 20px">
          <el-row :gutter="3">
            <el-col :span="4">
              <label class="item-title">
                SPU陈列图
                <b>*</b>
              </label>
            </el-col>
            <el-col :span="20">
              <el-upload
                :class="{hideUpload:displayList.length > 0}"
                :disabled="isPreview"
                :action="uploadUrl"
                :data="updateDataSpu"
                :limit="1"
                :headers="myHeaders"
                :on-success="displaySuccess"
                :file-list="displayList"
                list-type="picture-card"
                :on-remove="displayRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item style="margin-top: 20px">
          <el-row :gutter="3">
            <el-col :span="4">
              <label class="item-title"> SPU轮播图 </label>
            </el-col>
            <el-col :span="20">
              <el-upload
                :disabled="isPreview"
                :action="uploadUrl"
                :data="updateDataSpu"
                :headers="myHeaders"
                :on-success="bannerSuccess"
                list-type="picture-card"
                :file-list="bannerList"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="spuImgDeatail" style="margin-top: 20px">
          <el-row :gutter="3">
            <el-col :span="4">
              <label class="item-title">
                SPU详情
                <b>*</b>
              </label>
            </el-col>
            <el-col :span="20">
              <el-upload
                :disabled="isPreview"
                :action="uploadUrl"
                :data="updateDataSpu"
                :headers="myHeaders"
                :on-success="detailSuccess"
                list-type="picture-card"
                :file-list="detailList"
                :on-remove="detailRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <h2>
      <span>商品属性</span>
    </h2>
    <div class="product-attributes">
      <el-form
        ref="productAttributesForm"
        label-position="top"
      >
        <el-form-item
          v-for="item in productAttributesForms"
          :key="item.id"
        >
          <label class="item-title">
            {{ item.attributeName }}
            <b v-if="item.required === '1'">*</b>
          </label>
          <el-input
            :disabled="isPreview"
            v-if="item.attributeType === 'SPUATTRIBUTE02'"
            v-model="item.value"
            @input="item.value=item.value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
            placeholder=""></el-input>
          <el-select
            :disabled="isPreview"
            popper-class="select-class"
            :popper-append-to-body="false"
            v-if="item.attributeType === 'SPUATTRIBUTE01'"
            clearable
            v-model="item.value"
            :placeholder="$t('pleaseSelect')"
            class="question-input-width"
          >
            <el-option label="Yes" value="1"></el-option>
            <el-option label="No" value="0"></el-option>
          </el-select>
          <number-input
            :disabled="isPreview"
            v-model="item.value"
            class="question-input-width"
            v-if="item.attributeType === 'SPUATTRIBUTE03' || item.attributeType === 'SPUATTRIBUTE04'"
          ></number-input>
        </el-form-item>
      </el-form>
    </div>
    <h2>
      <span>商品规格</span>
    </h2>
    <SkuForm
      ref="skuForm"
     :source-attribute="sourceAttribute"
     :attribute.sync="attribute"
     :sku.sync="skuList"
     :structure="structure"
     :theme="2"
    >
      <template #skuImage="slotProps">
        <div class="image-upload-container">
            <el-image v-if="slotProps.row.skuImage" :src="slotProps.row.skuImage" :preview-src-list="[slotProps.row.skuImage]" fit="cover" title="点击预览" />
            <el-upload
             :show-file-list="false"
             :action="uploadUrl"
             :headers="myHeaders"
             :data="{fileFlag:'SKU', spuCode: updateDataSku.spuCode, skuCode:slotProps.row.skuCode || '' }"
             :before-upload="beforeUpload"
             :disabled="isPreview"
             :on-success="res => imageUpload(res, slotProps)"
             class="images-upload">
                <el-button size="small" icon="el-icon-upload2" :disabled="isPreview" v-if="!slotProps.row.skuImage">上传图片</el-button>
            </el-upload>
            <el-button :disabled="isPreview" v-if="slotProps.row.skuImage" size="small" icon="el-icon-delete" @click="imageRemove(slotProps)" />
        </div>
    </template>
    <template #skuCode="slotProps">
      {{ slotProps.row.skuCode }}
    </template>
     <template #isUseRealStock="slotProps">
        <el-checkbox
         :disabled="isPreview"
         v-model="slotProps.row.isUseRealStock"
         true-label="1"
         false-label="0"
        ></el-checkbox>
    </template>
    <template #useRealStock="slotProps">
      {{ slotProps.row.useRealStock }}
    </template>
    <template #usableStock="slotProps">
      <el-input
       v-if="slotProps.row.isUseRealStock !== '1'"
       type="number"
       size="small"
       :disabled="isPreview"
       v-model="slotProps.row.usableStock"
       @input="slotProps.row.usableStock=slotProps.row.usableStock.replace(/\D/g,'')"
       ></el-input>
    </template>
    </SkuForm>
    <bottom-btn
      @cancel="handleCancel"
      @save="handleSave('save')"
      :showSave="showSave"
      :nextName="$t('Next')"
      @next="next"
      style="margin-top: 20px"
    ></bottom-btn>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/config/variableInit'
import SkuForm from '../../components/skuForm.vue'
import addCategories from './components/addCategories'
import BottomBtn from '../../commons/BottomBtn'
import { mapGetters } from 'vuex'
import Ellipsis from '@/components/Ellipsis'
import addLabel from './components/addLabel'
import {
  getTree,
  getFrontCatalog,
  getSpuById
} from '@/api/product'
import NumberInput from '@/components/NumberInput/index'
import { validateURL } from '@/utils/validate'
import { reject } from 'lodash'
export default {
  name: 'StepOne',
  props: ['model', 'type', 'operationType', 'isShow'],
  components: {
    addCategories,
    BottomBtn,
    SkuForm,
    NumberInput,
    Ellipsis,
    addLabel
  },
  data () {
    var validateUrl = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateURL(value)) {
        callback(new Error(this.$t('pictureUrlError')))
      } else {
        callback()
      }
    }
    return {
      sourceAttribute: [],
      structure: [
        {
          name: 'id',
          type: 'slot',
          label: 'id'
        },
        {
          name: 'skuImage',
          type: 'slot',
          label: '图片'
        },
        {
          name: 'skuCode',
          type: 'slot',
          label: 'SKU编码'
        },
        {
          name: 'extNo',
          type: 'input',
          label: '物料编号',
          required: true
        },
        {
          name: 'isUseRealStock',
          type: 'slot',
          label: '使用实际库存',
          defaultValue: '0'
        },
        {
          name: 'useRealStock',
          type: 'slot',
          label: '可用实际库存'
        },
        {
          name: 'usableStock',
          type: 'slot',
          label: '可用虚拟库存'
        }
      ],
      attribute: [],
      skuList: [],
      spuImageList: [],
      tagDatas: [],
      fileList: [],
      displayList: [],
      bannerList: [],
      detailList: [],
      oneData: {
        productName: '',
        productDescribe: '',
        productType: '',
        isCreditsExchange: '0',
        isDelivery: '0'
      },
      uploadUrl: process.env.VUE_APP_BASE_URL + '/admin/upload/uploadFile',
      myHeaders: { Authorization: Vue.ls.get(ACCESS_TOKEN) },
      updateDataSpu: {
        fileFlag: 'SPU',
        spuCode: ''
      },
      updateDataSku: {
        fileFlag: 'SKU',
        spuCode: ''
      },
      spuCode: '',
      exchange: '',
      delivery: '',
      shipmentDatas: [],
      shipmentCoutry: [],
      shopmentLoading: false,
      isAdd: false,
      oldInitDatas: {},
      isEdit: false,
      selCateId: [],
      categoryList: [],
      catelogList: [],
      catalogId: '',
      productType: '',
      countryTypes: [],
      orgList: [],
      selectedOrgList: [],
      spuImgForm: {
        spuImgList: []
      },
      tempImgList: '',
      props: {
        value: 'id',
        label: 'catalogName'
      },
      addDialogShow: false,
      showNameRequire: false,
      showDescRequire: false,
      showList: {
        productNameLanguageList: false,
        productDescribeLanguageList: false
      },
      coutryChange: false,
      langDatas: {},
      langDataDesc: {},
      productCategories: [],
      productAttributesForm: {
        fit: '',
        brand: '',
        height: ''
      },
      productAttributesForms: [],
      catalogChanged: false,
      spuImgRules: {
        validator: validateUrl,
        trigger: 'blur'
      },
      payment: {
        bonusPeriod: 0
      },
      proDatas: [],
      edited: false,
      isPreview: false,
      showSave: false
    }
  },
  watch: {
    nowDataString: {
      handler (val) {
        if (val) {
          this.edited = true
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['lookupItems']),
    nowDataString () {
      return (
        JSON.stringify(this.productAttributesForms) +
        JSON.stringify(this.productCategories) +
        JSON.stringify(this.catalogId) +
        JSON.stringify(this.langDatas) +
        JSON.stringify(this.langDataDesc) +
        JSON.stringify(this.countryTypes) +
        JSON.stringify(this.model) +
        JSON.stringify(this.payment) +
        JSON.stringify(
          this.$refs.productSku && this.$refs.productSku.tableData
        ) +
        JSON.stringify(
          this.$refs.productSku && this.$refs.productSku.optionsDatas
        )
      )
    }
    // ,
    // showSave () {
    //   let flag = false
    //   if (this.operationType === 'edit' && this.isShow) {
    //     flag = true
    //   }
    //   return flag
    // }
  },
  mounted () {
    if (this.operationType && this.operationType !== 'add') {
      this.getDetail(this.operationType)
      this.isPreview = this.model.isPreview || false
    }
  },
  created () {
    this.getCatelogSelect()
  },
  methods: {
    update (data) {
      this.sourceAttribute = data
    },
    addAttr () {
      this.sourceAttribute.push({
        name: '',
        item: []
      })
    },
    beforeUpload (file) {
      const ext = ['jpg', 'png', 'gif', 'bmp']
      const size = 2
      const fileName = file.name.split('.')
      const fileExt = fileName[fileName.length - 1]
      const isTypeOk = ext.indexOf(fileExt) >= 0
      const isSizeOk = file.size / 1024 / 1024 < size
      if (!isTypeOk) {
        this.$message.error(`上传图片只支持 ${ext.join(' / ')} 格式！`)
      }
      if (!isSizeOk) {
        this.$message.error(`上传图片大小不能超过 ${size}MB！`)
      }
      return isTypeOk && isSizeOk
    },
    handleImgChange (file, fileList, key) {
      if (file.status === 'ready') {
        this.$set(file, 'progressFlag', true)
        this.$set(file, 'progressPercent', 0)
        const interval = setInterval(_ => {
          if (file.progressPercent >= 99) {
            clearInterval(interval)
            return
          }
          file.progressPercent += 1
        }, 10)
      }
      if (file.status === 'success') {
        file.progressFlag = false
      }
    },
    // 图片上传
    imageUpload (res, data) {
      this.updateDataSpu.spuCode = res.obj.spuCode
      this.updateDataSku.spuCode = res.obj.spuCode
      data.row.skuImage = res.obj.path
      this.$set(data.row, 'skuCode', res.obj.skuCode)
      this.$message.success('图片上传成功')
      this.$refs.skuForm.validateFieldByRows(data.$index, 'image', () => {})
    },
    imageRemove (data) {
      data.row.skuImage = ''
    },
    // 上传
    displaySuccess (res, file, fileList) {
      this.updateDataSpu.spuCode = res.obj.spuCode
      this.updateDataSku.spuCode = res.obj.spuCode
      this.displayList = fileList
      this.spuCode = res.obj.spuCode
      let flag = false
      this.spuImageList.forEach(item => {
        if (item.imageType === 'IMAGETYPE001') {
          flag = true
        }
      })
      if (flag) {
        return false
      }
      this.spuImageList.push({
        path: res.obj.path,
        imageType: 'IMAGETYPE001'
      })
    },
    bannerSuccess (res) {
      this.updateDataSpu.spuCode = res.obj.spuCode
      this.updateDataSku.spuCode = res.obj.spuCode
      this.spuCode = res.obj.spuCode
      this.spuImageList.push({
        path: res.obj.path,
        imageType: 'IMAGETYPE002'
      })
    },
    detailSuccess (res, file, fileList) {
      this.updateDataSpu.spuCode = res.obj.spuCode
      this.updateDataSku.spuCode = res.obj.spuCode
      this.spuCode = res.obj.spuCode
      this.detailList = fileList
      this.spuImageList.push({
        path: res.obj.path,
        imageType: 'IMAGETYPE003'
      })
    },
    onError () {
      this.$alert('上传失败，请稍后再试')
    },
    displayRemove (file) {
      this.displayList = []
      this.spuImageList.forEach(item => {
        item.url = item.path
      })
      this.spuImageList = reject(this.spuImageList, { url: file.url })
    },
    detailRemove (file, fileList) {
      this.detailList = fileList
      this.spuImageList.forEach(item => {
        item.url = item.path
      })
      this.spuImageList = reject(this.spuImageList, { url: file.url })
    },
    handleRemove (file) {
      this.spuImageList.forEach(item => {
        item.url = item.path
      })
      this.spuImageList = reject(this.spuImageList, { url: file.url })
    },
    // 添加shipment
    handleAddShipment () {
      const params = {
        toOrgIdList: this.countryTypes,
        fromOrgIdList: this.shipmentCoutry
      }
      this.$alert(params)
      this.shopmentLoading = true
    },
    // catelog搜索
    handleCatelogFilter (node, keyword) {
      return node.text.toLowerCase().includes(keyword.toLowerCase())
    },
    // 获取catelog列表
    getCatelogSelect () {
      const self = this
      getTree().then(response => {
        const data = response
        if (data) {
          if (Number(data.code) === 1) {
            const obj = data.obj || []
            obj.forEach(item => {
              if (item.children && item.children.length > 0) {
                item.children.forEach(subItem => {
                  if (!(subItem.children && subItem.children.length > 0)) {
                    subItem.disabled = true
                  }
                })
              } else {
                item.disabled = true
              }
            })
            self.catelogList = obj
          } else {
            this.$confirm(self.$t(data.code), {
              confirmButtonText: this.$t('confirmOK'),
              showCancelButton: false
            })
          }
        }
      })
    },
    // 选择改变catelog
    changeCatelogId (val) {
      this.catalogChanged = true
      this.catalogId = val[val.length - 1]
      this.listAttributeByCatalogId()
    },
    // 编辑时，初始化页面数据
    initDatas (initDatas) {},
    // 根据catelog id获取
    listAttributeByCatalogId () {
      if (this.oneData.selCateId && this.oneData.selCateId.length > 2) {
        const id = this.oneData.selCateId[2]
        getFrontCatalog(id).then(response => {
          const data = response
          if (data.obj && data.obj.attrList) {
            const productAttributesForms = []
            data.obj.attrList.forEach(item => {
              const arr = {
                attributeId: item.id,
                attributeName: item.attributeName,
                attributeType: item.attributeType,
                value: '',
                required: item.required
              }
              productAttributesForms.push(arr)
            })
            this.productAttributesForms = productAttributesForms
          }
        }).catch(error => {
          this.$confirm(error, {
            confirmButtonText: this.$t('confirmOK'),
            showCancelButton: false
          })
        })
      } else {
        this.$confirm('请选择三级类目', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false,
          callback: () => {
            this.oneData.selCateId = []
          }
        })
      }
    },
    // 设置category
    setCate (data) {
      this.model.categoryDatas = data
      this.coutryChange = true
    },
    // 删除对应的category
    removeCate (index, key) {
      this.model.categoryDatas[key].splice(index, 1)
      this.coutryChange = true
    },
    removeLabel (row) {
      this.tagDatas.splice(this.tagDatas.indexOf(row), 1)
    },
    // 展示添加category弹框
    showAddCate () {
      this.addDialogShow = true
      const channelArr = this.getChannelArr()
      let nowChannel = 'APP'
      if (channelArr.length === 1) {
        nowChannel = channelArr[0]
      }
      this.$nextTick((_) => {
        this.$refs.addCate.showAddProduct(this.model.categoryDatas, nowChannel)
      })
    },
    showAddLabel () {
      const idList = []
      if (this.tagDatas && this.tagDatas.length > 0) {
        this.tagDatas.forEach(item => {
          idList.push(item.id)
        })
      }
      this.$refs.addLabel.showAddLabel = true
      this.$refs.addLabel.fetchList(idList)
    },
    getTagList (data) {
      data.forEach(item => {
        this.tagDatas.push(item)
      })
    },
    getChannelArr () {
      const channelArr = []
      const list = this.model.categoryDatas
      // eslint-disable-next-line no-unused-vars
      for (const key in list) {
        if (list[key].length > 0) {
          channelArr.push(key)
        }
      }
      return channelArr
    },
    // 关闭category弹框
    closeCate () {
      this.addDialogShow = false
    },
    // 点击下一步
    next () {
      this.handleSave('next')
    },
    getDetail (type) {
      this.$parent.pageLoading = true
      getSpuById(this.model.id).then(result => {
        if (Number(result.code) === 1) {
          this.proDatas = result.obj
          const proDatas = result.obj
          const datas = this.oneData
          datas.productName = proDatas.productName
          datas.productDescribe = proDatas.productDescribe
          datas.productType = proDatas.productType
          datas.isCreditsExchange = proDatas.isCreditsExchange
          datas.isDelivery = proDatas.isDelivery
          this.tagDatas = proDatas.spuLabelList
          this.productAttributesForms = proDatas.spuAttributeList
          if (type !== 'copy') {
            datas.selCateId = [proDatas.firstId, proDatas.secondId, proDatas.thirdId]
            this.updateDataSpu.spuCode = proDatas.spuCode
            this.updateDataSku.spuCode = proDatas.spuCode
            this.spuCode = proDatas.spuCode
            this.spuImageList = proDatas.spuImageList
            proDatas.spuImageList.forEach(item => {
              if (item.imageType === 'IMAGETYPE001') {
                this.displayList.push({ url: item.path })
              }
              if (item.imageType === 'IMAGETYPE002') {
                this.bannerList.push({ url: item.path })
              }
              if (item.imageType === 'IMAGETYPE003') {
                this.detailList.push({ url: item.path })
              }
            })
          }
          // 前台类目
          if (type !== 'copy') {
            const addList = {}
            proDatas.categoryList.forEach((item) => {
              const list = []
              if (item.orgId) list.push(item.orgId)
              if (item.firstId) list.push(item.firstId)
              if (item.secondId) list.push(item.secondId)
              if (item.thirdId) list.push(item.thirdId)
              const channel = item.channelCode
              if (!addList[channel]) addList[channel] = []
              addList[channel].push({
                id: type !== 'copy' ? item.id : '',
                channel: item.channelCode,
                list: list,
                orgId: item.orgId,
                label: item.label
              })
            })
            this.catalogId = proDatas.catalogId
            this.model.categoryDatas = {}
            this.model.categoryDatas = addList
          }

          // 商品规格
          const attributeDatas = []
          proDatas.responseSpuSkuVo.spuSkuAttributeList.forEach((item1, index) => {
            // console.log(item1)
            attributeDatas.push({
              name: item1.label,
              item: []
            })
            item1.spuSkuAttibuteValueList.forEach(item2 => {
              attributeDatas[index].item.push({
                label: attributeDatas[index].name,
                value: item2.value,
                path: type !== 'copy' ? item2.path : ''
              })
            })
          })
          // sku列表
          const skuArr = []
          proDatas.responseSpuSkuVo.responseSkuList.forEach(item => {
            const arr = {}
            if (type !== 'copy') {
              arr.id = item.id
              arr.skuCode = item.skuCode
              arr.skuImage = ''
              if (item.skuImageList.length > 0) {
                arr.skuImage = item.skuImageList[0].path
              }
            }
            arr.extNo = item.extNo
            arr.usableStock = item.usableStock
            arr.isUseRealStock = item.isUseRealStock
            if (item.skuAttributeList.length === 1) {
              arr.sku = item.skuAttributeList[0]
            } else {
              arr.sku = item.skuAttributeList
            }
            skuArr.push(arr)
          })
          setTimeout(() => {
            this.sourceAttribute = attributeDatas
            this.attribute = attributeDatas
            setTimeout(() => {
              this.skuList = skuArr
              this.$refs.skuForm.init()
            }, 100)
          }, 100)
          this.$parent.pageLoading = false
        } else {
          this.$parent.pageLoading = false
        }
      }).catch(() => {
        this.$parent.pageLoading = false
      })
    },
    // 保存按钮点击
    async handleSave (type) {
      // 后台类目判断
      if (!this.oneData.selCateId) {
        this.$confirm(this.$t('productCenter.needCatalog'), {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      // 商品类型判断
      if (!this.oneData.productType) {
        this.$confirm('请选择商品类型', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      // 商品名称判断
      if (!this.oneData.productName) {
        this.$confirm('商品名称不能为空', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      if (!this.tagDatas || this.tagDatas.length < 1) {
        this.$confirm('请选择商品标签', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      if (this.displayList.length < 1) {
        this.$confirm('请上传SPU陈列图', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      if (this.detailList.length < 1) {
        this.$confirm('请上传SPU详情图', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      let attrFlag = false
      this.productAttributesForms.forEach(item => {
        if (item.required === '1') {
          if (!item.value || item.value === '') {
            attrFlag = true
          }
        }
      })
      if (attrFlag) {
        this.$alert('商品属性必填字段不能为空')
        return false
      }
      const labelList = []
      this.tagDatas.forEach(item => {
        labelList.push({ labelId: item.id })
      })
      if (this.skuList[0].sku === '' || this.skuList[0].sku[0] === '') {
        this.$confirm('请至少添加一条商品规格信息', {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      // sku数据
      const skuLists = []
      this.skuList.forEach(item => {
        const arr = {}
        arr.id = item.id || ''
        arr.skuCode = item.skuCode
        arr.extNo = item.extNo
        arr.usableStock = item.usableStock
        arr.isUseRealStock = item.isUseRealStock
        if (!item.sku[0]) {
          arr.skuAttributeList = [item.sku]
        } else {
          arr.skuAttributeList = item.sku
        }
        arr.skuImage = {
          path: item.skuImage,
          imageType: 'IMAGETYPE001'
        }
        skuLists.push(arr)
      })
      let extNoFlag = false
      let typeFlag = ''
      skuLists.forEach(item => {
        if (!item.extNo || item.extNo === '') {
          extNoFlag = true
        }
        if (this.oneData.productType === 'PRODUCTTYPE01' && item.isUseRealStock === '0') {
          typeFlag = 1 // 1为附件商品
        }
        if (this.oneData.productType === 'PRODUCTTYPE02' && item.isUseRealStock === '1') {
          typeFlag = 2 // 2为服务包商品
        }
      })
      if (extNoFlag) {
        this.$alert('请填写物料编号')
        return false
      }
      if (typeFlag === 1) {
        this.$alert('附件商品请使用实际库存')
        return false
      }
      if (typeFlag === 2) {
        this.$alert('服务包商品请使用虚拟库存')
        return false
      }
      if (this.operationType !== 'add') {
        const proDatas = this.proDatas.responseSpuSkuVo.responseSkuList
        proDatas.forEach(item1 => {
          skuLists.forEach(item2 => {
            if (item2.id === item1.id) {
              if (this.operationType === 'copy') {
                item1.skuPriceList.forEach(item3 => {
                  item3.id = ''
                })
              }
              item2.skuPriceList = item1.skuPriceList
            }
          })
        })
      }
      const submitDatas = {
        catalogId: this.oneData.selCateId[2],
        productName: this.oneData.productName,
        productDescribe: this.oneData.productDescribe,
        productType: this.oneData.productType,
        spuCode: this.spuCode,
        labelList: labelList,
        categoryList: [],
        isCreditsExchange: this.oneData.isCreditsExchange || 0,
        isDelivery: this.oneData.isDelivery || 0,
        spuImageList: this.spuImageList,
        spuAttributeList: this.productAttributesForms,
        skuList: skuLists
      }
      if (this.operationType !== 'copy') {
        submitDatas.id = this.model.id
      } else {
        submitDatas.spuAttributeList.forEach(item => {
          item.id = ''
        })
      }
      // 设置categoryList
      const categoryDatas = this.model.categoryDatas
      const newCategoryList = []
      const keys = Object.keys(categoryDatas)
      keys &&
        keys.forEach((key) => {
          categoryDatas[key].forEach((item) => {
            const obj = {
              channelCode: key,
              channelName: key,
              orgId: item.orgId,
              categoryId: item.list[item.list.length - 1],
              id: item.id,
              isDeleted: item.isDeleted
            }

            newCategoryList.push(obj)
          })
        })
      if (newCategoryList.length === 0) {
        this.$confirm(this.$t('productCenter.requireCategory'), {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      submitDatas.categoryList = newCategoryList

      // 属性判断
      if (newCategoryList.length === 0) {
        this.$confirm(this.$t('productCenter.requireCategory'), {
          confirmButtonText: this.$t('confirmOK'),
          showCancelButton: false
        })
        return false
      }
      if (this.operationType !== 'add' && this.proDatas.responseSpuSkuVo && this.proDatas.responseSpuSkuVo.responseAutoOnOffSetVo) {
        if (this.operationType === 'copy') {
          this.proDatas.responseSpuSkuVo.responseAutoOnOffSetVo.id = ''
          this.proDatas.responseSpuSkuVo.responseAutoOnOffSetVo.spuId = ''
        }
        submitDatas.shelvesConfig = this.proDatas.responseSpuSkuVo.responseAutoOnOffSetVo
      }
      // 设置存在的channel
      const channelArr = this.getChannelArr()
      this.$set(this.model, 'channels', channelArr)
      this.$emit('startLoading')
      this.$emit('submit', submitDatas, type, this.operationType)
    },

    // 返回按钮点击
    handleBack () {
      this.$emit('back', this.model)
    },
    // 取消按钮点击
    handleCancel () {
      this.$emit('cancel')
    },
    // 根据后台数据设置属性的规则
    getRules (item) {
      if (item.required === 'REQUIRED') {
        return {
          required: true,
          message: this.$t('productCenter.requireAttr'),
          trigger: item.attributeType === 'MDSETYPE01' ? 'change' : 'blur'
        }
      }

      return {}
    },
    bonusPeriodChange (val) {
      if (!val) {
        this.$nextTick((_) => {
          this.payment.bonusPeriod = 0
        })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import '@/styles/variables.scss';
.source {
  margin-top: 0px;
}
.country-box {
  margin-top: 10px;
}
.el-form-item {
  margin-bottom: 0px;
  position: relative;
}
/deep/ .el-form-item__content {
  line-height: 30px !important;
}
.thisStepStyle {
  margin-top: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 5px;
  padding: 15px 15px 0px 15px;
}
.spuImage {
  margin-right: 10px;
}
.addImageSty {
  float: right;
  font-size: 12px;
  text-align: center;
  margin-bottom: 10px;
}
.stepButtonSty {
  margin: auto;
  margin-top: 10px;
}
.spu-img {
  margin: 10px 0;
  .img-form {
    margin-bottom: 20px;
  }
  .img-body {
    .img-item {
      display: flex;
      align-items: center;
      i {
        margin-left: 10px;
      }
    }
  }
}
.demo-image {
  clear: both;
}
.el-upload-list__item {
  display: inline-block;
  width: 300px;
}
.upload-demo {
  margin-top: 10px;
}
.product-attributes {
  .el-form {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      margin: 10px;
      flex: 30%;
    }
  }
}
.img-title {
  b {
    margin-left: 5px;
    color: red;
    font-size: 16px;
  }
}
h2 {
  background: #f4f4f4;
  border-left: 4px solid #00aca1;
  line-height: 30px;
  font-size: 14px;
  padding-left: 10px;
}
.cateBox {
  display: inline-block;
  border: 1px solid #979797;
  padding: 5px 10px;
  min-width: 40%;
  .el-tag {
    margin-right: 10px;
  }
}
.item-title {
  line-height: 40px;
  b {
    font-size: 16px;
    color: red;
  }
}
.source {
  margin-top: 0px;
}
.mb10 {
  margin-bottom: 10px;
}
.ml20 {
  margin-left: 20px;
}
.product-detail-payment {
  margin-bottom: 20px;
  .payment-col {
    height: 42px;
  }
  .payment-item {
    transform: translateY(-50%);
    top: 50%;
  }
  .select-up {
    z-index: 99;
  }
}
/deep/ .el-upload-dragger {
    width: initial;
    height: initial;
    border: 0;
    border-radius: 0;
    background-color: initial;
    overflow: auto;
}
.image-upload-container {
    .el-image {
        vertical-align: middle;
        margin: 0 5px;
        width: 30px;
        height: 30px;
    }
    .images-upload,
    > .el-button {
        display: inline-block;
        margin: 0 5px;
        vertical-align: middle;
    }
}
.hideUpload /deep/ .el-upload{
  display:none;   /* 上传按钮隐藏 */
}
</style>
